const { BrowserWindow, ipcMain, Menu, app, session, dialog } = require('electron')
const path = require('path')
const Store = require('electron-store')
const { postRefreshToken, getAccessToken, uploadVideo, getCustomReport, postWeekScheduleUpdate } = require('../apis')
const store = new Store()
const isDevelopment = process.env.NODE_ENV === 'development'
let mainWindow = null
let refreshTimer = null
let videoPath = []
function scheduleAutoRefresh() {
  clearTimeout(refreshTimer)
  const expiresAt = store.get('expires_in')
  if (!expiresAt) return
  // 提前5分钟触发刷新
  const refreshTime = expiresAt - Date.now() - 300000
  if (refreshTime > 0) {
    refreshTimer = setTimeout(async () => {
      const refresh_token = store.get('refresh_token')
      await postRefreshToken(refresh_token)
    }, refreshTime)
  }
}
function isAuthValid() {
  const refresh_token_expires_in = store.get('refresh_token_expires_in')
  if (Date.now() > refresh_token_expires_in) {
    forceLogout()
    return false
  }
  const access_token = store.get('access_token')
  const expiresAt = store.get('expires_in') // 获取存储的过期时间戳
  if (!access_token || !expiresAt) {
    return false
  }
  return Date.now() < expiresAt // 对比当前时间
}
function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1160,
    height: 752,
    minHeight: 632,
    minWidth: 960,
    // show: false,
    // frame: false,
    title: '肉鸡上传器',
    webPreferences: {
      nodeIntegration: true,
      preload: path.resolve(__dirname, '../utils/contextBridge.js')
    },
    icon: path.resolve(__dirname, '../assets/logo.png')
  })
  Menu.setApplicationMenu(null)
  if (store.get('auth_code')) {
    scheduleAutoRefresh()
  }

  if (isDevelopment) {
    mainWindow.loadURL('http://localhost:8010/')
  } else {
    const entryPath = path.resolve(__dirname, '../../build/index.html')
    mainWindow.loadFile(entryPath)
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
  // mainWindow.webContents.send('AuthValid', '65516516')

  mainWindowListenEvents()
}
function transformFilePaths(filePaths) {
  return filePaths.map((path) => {
    const parts = path.split('\\')
    const name = parts[parts.length - 1]
    return {
      path,
      name
    }
  })
}
function mainWindowListenEvents() {
  ipcMain.on('mainWindow-min', () => {
    mainWindowIsExist() && mainWindow.minimize()
  })

  ipcMain.on('mainWindow-max', () => {
    if (mainWindowIsExist()) {
      mainWindow.maximize()
      mainWindow.webContents.send('mainWindowIsMax', true)
    }
  })

  ipcMain.on('mainWindow-restore', () => {
    if (mainWindowIsExist()) {
      mainWindow.unmaximize()
      mainWindow.webContents.send('mainWindowIsMax', false)
    }
  })

  ipcMain.on('mainWindow-close', () => {
    mainWindowIsExist() && mainWindow.hide()
  })

  ipcMain.on('mainWindow-open-devtool', () => {
    mainWindowIsExist() && mainWindow.webContents.openDevTools()
  })
  ipcMain.on('AuthValid', (event) => {
    mainWindow.webContents.send('is-AuthValid', isAuthValid())
  })
  ipcMain.on('logout', (event) => {
    forceLogout()
    mainWindow.webContents.send('is-AuthValid', isAuthValid())
  })
  ipcMain.on('clear-video', async () => {
    console.log('清除视频')
    videoPath = []
  })

  ipcMain.on('open-dialog', (event, cb) => {
    dialog
      .showOpenDialog({
        title: '选择视频素材',
        properties: ['openFile', 'multiSelections'],
        filters: [{ name: '视频文件', extensions: ['mp4', 'mov', 'avi'] }]
      })
      .then((result) => {
        if (!result.canceled) {
          // 发送消息到渲染进程
          mainWindow.webContents.send('dialog-result', transformFilePaths(result.filePaths))
        }
        if (result.filePaths) {
          videoPath = transformFilePaths(result.filePaths)
        }
      })
  })
  ipcMain.handle('send-video', async (_, options) => {
    try {
      // 自动携带认证信息
      const res = await uploadVideo(options)
      if (res.code === 0) {
        videoPath = videoPath.filter((item) => item.name !== options.filename)
      }
      mainWindow.webContents.send('video-result', { ...res, videoPath })
    } catch (error) {
      console.log(error, 'e')
    }
  })
  ipcMain.handle('custom-report', async (_, options) => {
    try {
      // 自动携带认证信息
      const res = await getCustomReport(options)
      mainWindow.webContents.send('custom-report-result', {
        [options.advertiser_id]: res
      })
    } catch (error) {
      console.log(error, 'e')
    }
  })
  ipcMain.handle('update-project', async (_, options) => {
    try {
      // 自动携带认证信息
      const res = await postWeekScheduleUpdate(options)
      mainWindow.webContents.send('update-project-result', {
        [options.advertiser_id]: res
      })
    } catch (error) {
      console.log(error, 'e')
    }
  })
}

function mainWindowIsExist() {
  return mainWindow && !mainWindow.isDestroyed()
}

function getMainWindow() {
  return mainWindow
}
function forceLogout() {
  store.clear()
  clearTimeout(refreshTimer)
}

// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
  const mainSession = session.defaultSession
  // 监听所有网络请求
  mainSession.webRequest.onBeforeRequest(async (details, callback) => {
    if (details.url.includes('www.srgyrhbw.cn')) {
      const str = details.url
      const startIndex = str.indexOf('auth_code=')
      if (startIndex !== -1) {
        const newStartIndex = startIndex + 'auth_code='.length
        const endIndex = str.indexOf('&', newStartIndex)
        const authCode = endIndex === -1 ? str.slice(newStartIndex) : str.slice(newStartIndex, endIndex)
        const data = await getAccessToken(authCode)
        const { access_token, expires_in, refresh_token, refresh_token_expires_in } = data
        store.set('access_token', access_token)
        store.set('expires_in', expires_in * 1000 + Date.now())
        store.set('refresh_token', refresh_token)
        store.set('refresh_token_expires_in', refresh_token_expires_in * 1000 + Date.now())
        scheduleAutoRefresh() // 存储后启动刷新定时器
        if (isDevelopment) {
          await mainWindow.loadURL('http://localhost:8010/')
        } else {
          const entryPath = path.resolve(__dirname, '../../build/index.html')
          mainWindow.loadFile(entryPath)
        }
        mainWindow.webContents.send('is-AuthValid', isAuthValid())
      } else {
        console.log('未找到 auth_code')
      }
    }
    callback({ cancel: false }) // 不取消请求
  })
})
module.exports = {
  getMainWindow,
  createMainWindow,
  mainWindowIsExist
}
